package mainpackage;

import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.table.TableModel;

/**
 * JTableUtils is a utilities class that can retrieve data from a JTable.
 * @author Eric Kisner
 */
public class JTableUtils {

    /**
     * Returns all values of a JTable as a Collection of a collection of strings, which represents
     * a Collection of rows.
     * @param numRows The number of rows in the JTable.
     * @param numColumns The number of columns in the JTable.
     * @param table The JTable we want to extract data from.
     * @return A collection of 'rows'.
     */
    public static ArrayList<ArrayList<String>> dataFromTable( JTable table ) {
        TableModel m = table.getModel();
        int numRows = m.getRowCount();
        int numColumns = m.getColumnCount();
        ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
        for( int i = 0; i < numRows; i++ ) {
            ArrayList<String> row = new ArrayList<String>();
            for( int j = 0; j < numColumns; j++ ) {
                String cellVal = (String) m.getValueAt( i, j );
                if( cellVal != null ) cellVal = cellVal.trim();
                row.add( cellVal );
            }
            ret.add( row );
        }
        return ret;
    }
}
